package io.renren.modules.h5.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.WriterException;
import io.renren.common.sms.AliyunSms;
import io.renren.common.utils.*;
import io.renren.common.weixin.payutils.WXJSShare;
import io.renren.modules.noc.controller.BaseController;
import io.renren.modules.noc.entity.*;
import io.renren.modules.noc.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.*;

/**
 * 展会
 *
 * @author whc
 * @email hucheng_86@126.com
 * @date 2019-04-03 22:37:46
 */
@Controller
@RequestMapping("/h5")
public class NoMobileController extends BaseController{
    @Autowired
    private NocMemberService nocMemberService;
    @Autowired
    private NocReadCardService nocReadCardService;
    @Autowired
    private NocTemplateService nocTemplateService;
    @Autowired
    private NocWenjuanService nocWenjuanService;
    @Autowired
    private NocLyService nocLyService;
    @Autowired
    private NocBusinessService nocBusinessService;
    @Autowired
    private NocRegionService nocRegionService;

    @Value("${ad.short.url}")
    private String shortUrl;
    @Value("${ercode.pre}")
    private String _pre;


    @Value("${sms.aliyun.tongxing.signName}")
    private String smsTongxingSignName;
    @Value("${sms.aliyun.tongxing.template}")
    private String smsTongxingTemplate;



    @Autowired
    private WXJSShare wxjsShare;

    //同行短信-阿里云
    //private final String _txMsg = "尊敬的{0},{1}帮您注册的{2}的预登记观众电子门票链接 {3} ";

    //下面这两条阿里发送不了
    private final String _yqMsg = "{0}您好，您的朋友{1}邀请您注册为{2}专业观众,体验链接：{3} ";
    private final String _yqMsgl = "{0}您好，您的朋友{1}邀请您注册为{2}预登记观众,体验链接：{3} ";
    public static final String RANDOMCODEKEY= "RANDOMREDISKEY";

    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public String show() {
        return "modules/h5/show";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(String s,HttpServletRequest req) {
        if(StringUtils.isEmpty(s)){
            s = "3";
        }
        req.setAttribute("s",s);
        String tid = req.getParameter("tid");
        String ly = req.getParameter("ly");
        String memberId = req.getParameter("id");
        Session session = this.getSession();
        //判断是否微信端注册
        Map wxUser = (HashMap) session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if (wxUser != null) {
            String openId = (String) wxUser.get("openId");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("open_id", openId);
            map.put("tid",tid);
            map.put("pid",tid);
            //List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.listByMap(map);
            List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.getErcodeByOpenId(map);
            if (list != null && list.size() > 0) {
                NocMemberEntity member = list.get(0);
                String ercode = member.getCol20();
                if(StringUtils.isNotEmpty(ercode)) {
                    //已经生成二维码的
                    NocTemplateEntity nocTemplateEntity = nocTemplateService.getById(tid);
                    session.setAttribute("template", nocTemplateEntity);
                    return "redirect:ercode?tid=" + tid + "&id=" + member.getId() + "&ly=" + ly;
                }else{
                    //未生成二维码的
                    req.setAttribute("id",member.getId());
                    req.setAttribute("member",member);
                    this.memberTongx(tid,member.getId(),req);
                    return "modules/h5/detail";
                }
            }
        }

        //合并手机号和详细信息页面后
        if(StringUtils.isNotEmpty(memberId)){
            NocMemberEntity member = nocMemberService.getById(memberId);
            this.memberTongx(tid,Integer.parseInt(memberId),req);
            req.setAttribute("member",member);
        }

        if("2".equals(s)){
            req.setAttribute("title_zh","名片报名");
            req.setAttribute("title_en","Business card recognition");
        }else if("1".equals(s)){
            req.setAttribute("title_zh","入场凭证找回");
            req.setAttribute("title_en","Find registration back");
        }else{
            req.setAttribute("title_zh","展会注册报名");
            req.setAttribute("title_en","Personal Register");
        }
        return "modules/h5/index";
    }

    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String error() {
        return "modules/h5/error";
    }


    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    public String reg(String s,HttpServletRequest req) {
        req.setAttribute("s",s);
        String tid = req.getParameter("tid");
        String ly = req.getParameter("ly");
        Session session = this.getSession();
        //判断是否微信端注册
        Map wxUser = (HashMap) session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if (wxUser != null) {
            String openId = (String) wxUser.get("openId");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("open_id", openId);
            map.put("tid",tid);
            map.put("pid",tid);
            //List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.listByMap(map);
            List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.getErcodeByOpenId(map);
            if (list != null && list.size() > 0) {
                NocMemberEntity member = (NocMemberEntity) list.get(0);
                String ercode = member.getCol20();
                if(StringUtils.isNotEmpty(ercode)) {
                    //已经生成二维码的
                    NocTemplateEntity nocTemplateEntity = nocTemplateService.getById(tid);
                    session.setAttribute("template", nocTemplateEntity);
                    return "redirect:ercode?tid=" + tid + "&id=" + member.getId() + "&ly=" + ly;
                }else{
                    //未生成二维码的
                    req.setAttribute("id",member.getId());
                    req.setAttribute("member",member);
                    this.memberTongx(tid,member.getId(),req);
                    return "modules/h5/detail";
                }
            }
        }

        if("2".equals(s)){
            req.setAttribute("title_zh","名片报名");
            req.setAttribute("title_en","Business card recognition");
        }else if("1".equals(s)){
            req.setAttribute("title_zh","报到凭证找回");
            req.setAttribute("title_en","Find registration back");
        }else{
            req.setAttribute("title_zh","展会注册报名");
            req.setAttribute("title_en","Personal Register");
        }
        return "modules/h5/reg";
    }

    @RequestMapping(value = "/reg_en", method = RequestMethod.GET)
    public String reg_en() {
        return "reg_2en";
    }

    @RequestMapping(value = "/ercode")
    public String ercode(String id,HttpServletRequest request) {
        if(StringUtils.isNotEmpty(id)){
            request.setAttribute("id",id);
            request.setAttribute("member",nocMemberService.getById(id));
            return "modules/h5/ercode";
        }else{
            return "modules/404";
        }
    }

    @RequestMapping(value = "/invite", method = RequestMethod.GET)
    public String invite(String id,String ly,String tid ,HttpServletRequest req) {
        Map<String,Object> p = new HashMap<>();
        p.put("ly",ly);
        p.put("tid",tid);
        List<NocLyEntity> list = (List<NocLyEntity>) nocLyService.listByMap(p);
        if(list!=null&&list.size()>0) {
            NocLyEntity nocLyEntity = list.get(0);
            req.setAttribute("nocLyEntity",nocLyEntity);
        }
        StringBuffer url  = req.getRequestURL();
        String tempContextUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();

        req.setAttribute("id",id);
        req.setAttribute("member",nocMemberService.getById(id));
        req.setAttribute("basePath",tempContextUrl);
        return "modules/h5/invite";
    }

    @RequestMapping(value = "/help", method = RequestMethod.GET)
    public String help(String id,String ly,String tid ,HttpServletRequest req) {
        req.setAttribute("id",id);
        req.setAttribute("member",nocMemberService.getById(id));
        return "modules/h5/help";
    }

    /**
     * 获取短信验证码
     * @param mobile
     * @return
     */
    /*@RequestMapping("getCheckCode")
    @ResponseBody
    public R getCheckCode(String tid,String mobile) {
        Session session = this.getSession();
        // 发送短信，获取短信验证码
        String checkCode = this.sendCheckCode(tid,mobile);
        if (StringUtils.isNotBlank(checkCode)) {
            // 将验证码放入缓存中
            session.setAttribute("checkCode",checkCode);
            return R.ok("短信发送成功");
        } else {
            return R.error("短信发送失败");
        }
    }*/

    /**
     * 获取邮件验证码
     * @param mobile
     * @return
     */
    @RequestMapping("getMailCode")
    @ResponseBody
    public R getMailCode(String mobile) {
        Session session = this.getSession();
        // 发送短信，获取短信验证码
        String mailCode = EmailUtils.sendMailCode(mobile);
        if (StringUtils.isNotBlank(mailCode)) {
            // 将验证码放入缓存中
            session.setAttribute("mailCode",mailCode);
            return R.ok("Send eMail Success");
        } else {
            return R.error("Send eMail Fail");
        }
    }

    /**
     * 用户注册-中文
     * @param mobile
     * @param tcode
     * @param password
     * @return
     */
    @RequestMapping("doReg")
    public String doReg(String s,String mobile, String tcode, String password,HttpServletRequest request) {
        Session session = this.getSession();
        /*String _rdCode = (String)session.getAttribute("RANDOMREDISKEY");
        if(!StringUtils.isNotEmpty(tcode) || !(tcode.toUpperCase().equals(_rdCode))){
            request.setAttribute("msg","图形填写不正确！");
            return "modules/h5/reg";
        }*/
       /* String _ckCode = (String)session.getAttribute("checkCode");
        if (!(password.equals(_ckCode)||password.equals("110110"))) {

            request.setAttribute("msg","短信验证码填写不正确！");
            return "modules/h5/reg";
        }*/

        if(StringUtils.isEmpty(mobile)){
            return "modules/h5/index";
        }

        request.setAttribute("mobile",mobile);
        request.setAttribute("tcode",tcode);
        request.setAttribute("password",password);
        request.setAttribute("s",s);
        //0. 首先判断是不是展商
        Integer templateId = this.getDefaultTemplateIdNosession();
        String tid = (String)session.getAttribute("tid");
        Map<String,Object> busiMap = new HashMap<String,Object>();
        busiMap.put("mobile",mobile);
        busiMap.put("tid",tid);
        busiMap.put("pid",templateId);
        List<NocBusinessEntity> busiList = (List<NocBusinessEntity>)nocBusinessService.getErcodeByOpenId(busiMap);
        // 展商已注册
        if(busiList!=null&&busiList.size()>0) {
            NocBusinessEntity business = busiList.get(0);
            String erCode = business.getErcode();
            //已经生成了二维码的
            if (StringUtils.isNotEmpty(erCode)) {
                //openId与手机号进行绑定
                this.businessAddOpenId(business.getId());
                String ly = (String) session.getAttribute("ly");
                session.setAttribute("id", business.getId() + "");
                return "redirect:/busi/ercode?tid=" + tid + "&ly=" + ly;
            }
        }else {
            //观众
            //1. 如果已经注册，直接查询出二维码
            //2. 如果未注册，跳转到填写信息页面
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("col1", mobile);
            map.put("tid", tid);
            map.put("pid",templateId);
            System.out.println("参数col1="+mobile+"&tid="+tid+"&pid="+templateId);
            //List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.listByMap(map);
            List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.getErcodeByOpenId(map);
            //已注册
            if (list != null && list.size() > 0) {
                for(NocMemberEntity dto: list){
                    System.out.println(dto.getId()+"=="+dto.getCol20());
                }
                NocMemberEntity member = list.get(0);
                String erCode = member.getCol20();
                //已经生成了二维码的
                if (StringUtils.isNotEmpty(erCode)) {
                    //openId与手机号进行绑定
                    this.memberAddOpenId(member.getId());
                    String ly = (String) session.getAttribute("ly");
                    return "redirect:ercode?tid=" + tid + "&id=" + member.getId() + "&ly=" + ly;
                } else {
                    //未生成二维码的
                    request.setAttribute("id", member.getId());
                    request.setAttribute("member", member);
                    this.memberTongx(tid, member.getId(), request);
                    return "modules/h5/detail";
                }
                //未注册
            } else {
                //名片识别
                if ("2".equals(s)) {
                    return "modules/h5/mingpian";
                }
                NocMemberEntity t = new NocMemberEntity();
                t.setCol1(mobile);
                t.setTid(Integer.parseInt(tid));
                String ly = (String) session.getAttribute("ly");
                t.setLy(ly);
                //判断是否微信端注册
                Map wxUser = (HashMap) session.getAttribute(GlobalConstant.SESSION_WX_USER);
                if (wxUser != null) {
                    t.setOpenId((String) wxUser.get("openId"));
                }
                nocMemberService.save(t);
                request.setAttribute("id", t.getId());
                request.setAttribute("member", t);
                return "modules/h5/detail";
            }
        }
        return "modules/h5/index";
    }


    //新版注册2019-06-21
    @RequestMapping("doReg2")
    public String doReg2(String mobile, String tcode,String[] names,String[] mobiles,HttpServletRequest request) {
        Session session = this.getSession();
        /*String _rdCode = (String)session.getAttribute("RANDOMREDISKEY");
        if(!StringUtils.isNotEmpty(tcode) || !(tcode.toUpperCase().equals(_rdCode))){
            request.setAttribute("msg","图形填写不正确！");
            return "modules/h5/reg";
        }*/

       /* String _ckCode = (String)session.getAttribute("checkCode");
        if (!(password.equals(_ckCode)||password.equals("110110"))) {
            request.setAttribute("msg","短信验证码填写不正确！");
            return "modules/h5/reg";
        }*/

        if(StringUtils.isEmpty(mobile)){
            return "modules/h5/index";
        }

        String ly = request.getParameter("ly");
        String tid = request.getParameter("tid");
        String s = request.getParameter("s");
        String huiyibmb_cusname = request.getParameter("huiyibmb_cusname");
        String huiyibmb_canhren = request.getParameter("huiyibmb_canhren");
        String huiyibmb_Department = request.getParameter("huiyibmb_Department");
        String huiyibmb_zhiwu = request.getParameter("huiyibmb_zhiwu");
        String huiyibmb_sexly_Value = request.getParameter("huiyibmb_sexly_Value");
        String huiyibmb_mail = request.getParameter("huiyibmb_mail");
        String huiyibmb_col12 = request.getParameter("huiyibmb_col12");
        String huiyibmb_col13 = request.getParameter("huiyibmb_col13");
        String huiyibmb_col51 = "";
        if(tid.equals("11")){
             huiyibmb_col51 = request.getParameter("huiyibmb_col51");
        }
        Map<String,Object> pmap = new HashMap<>();
        pmap.put("id",request.getParameter("province"));
        String diqu = nocRegionService.getProvinceById(pmap).get("name")+request.getParameter("city");
        String huiyibmb_address = request.getParameter("huiyibmb_address");

        NocMemberEntity t = new NocMemberEntity();
        t.setCol1(mobile);
        t.setCol2(huiyibmb_cusname);
        t.setCol3(huiyibmb_canhren);
        t.setCol4(huiyibmb_Department);
        t.setCol5(huiyibmb_zhiwu);
        t.setCol6(huiyibmb_sexly_Value);
        t.setCol7(huiyibmb_mail);
        t.setCol9(huiyibmb_address);
        t.setCol12(huiyibmb_col12);
        t.setCol13(huiyibmb_col13);
        t.setCol51(huiyibmb_col51);
        t.setCol52(diqu);
        t.setLy(ly);
        t.setTid(Integer.parseInt(tid));
        //1. 如果已经注册，直接查询出二维码
        //2. 如果未注册，跳转到填写信息页面
        NocMemberEntity member = this.userIsExit(mobile,tid);
        //已注册
        if(member!=null){
            String erCode = member.getCol20();
            //已经生成了二维码的
            if(StringUtils.isNotEmpty(erCode)){
                //openId与手机号进行绑定
                this.memberAddOpenId(member.getId());
                return "redirect:ercode?tid="+tid+"&id="+member.getId()+"&ly="+ly;
            }else{
                //未生成二维码的
                //问卷没有填写完成的不生成二维码
                t.setId(member.getId());
                nocMemberService.updateById(t);
                doTongxing(tid,ly,names,mobiles,t,request);
                if(StringUtils.isNotEmpty(tid)){
                    String result = nocWenjuanService.getWenjuan(tid);
                    request.setAttribute("id",t.getId());
                    request.setAttribute("wenjuan",result);
                }
            }
        //未注册
        }else{
            //现场渠道的观众直接显示二维码（不显示问卷）
            if("xianchang".equals(ly)){
                //生成二维码
                t.setCol20(this.getNextErCode());
                //以生成二维码的时间为创建时间
                t.setCreateTime(new Date());
                //是否生成vip会员
                t.setCol15(this.isCreateVipMember(ly,tid));
                nocMemberService.save(t);
                //添加同行人员
                doTongxing(tid,ly,names,mobiles,t,request);
                if(StringUtils.isNotEmpty(tid)){
                    String result = nocWenjuanService.getWenjuan(tid);
                    request.setAttribute("wenjuan",result);
                }
                request.setAttribute("id",t.getId());
                request.setAttribute("member",t);
                return "modules/h5/ercode";
            }else{
                //问卷没有填写完成的不生成二维码
                nocMemberService.save(t);
                //添加同行人员
                doTongxing(tid,ly,names,mobiles,t,request);
                if(StringUtils.isNotEmpty(tid)){
                    String result = nocWenjuanService.getWenjuan(tid);
                    request.setAttribute("id",t.getId());
                    request.setAttribute("wenjuan",result);
                }
            }
        }
        request.setAttribute("mobile",mobile);
        request.setAttribute("tcode",tcode);
        request.setAttribute("s",s);
        return "modules/h5/wenjuan";
    }

    /*@RequestMapping("doRegEn")
    public String doRegEn(String mobile, String tcode, String password,HttpServletRequest request) {
        Session session = this.getSession();
        String _rdCode = (String)session.getAttribute("RANDOMREDISKEY");
        String _emCode = (String)session.getAttribute("checkCode");

        request.setAttribute("mobile",mobile);
        request.setAttribute("tcode",tcode);
        request.setAttribute("password",password);

        if (!(password.equals(_emCode)||password.equals("110110"))) {
            request.setAttribute("msg","Security is incorrect！");
            return "modules/h5/reg_en";
        }
        //1. 如果已经注册，直接查询出二维码
        //2. 如果未注册，跳转到填写信息页面
        String tid = (String)session.getAttribute("tid");
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("col1",mobile);
        map.put("tid",tid);
        List<NocMemberEntity> list = (List<NocMemberEntity>)nocMemberService.listByMap(map);
        if(list!=null&&list.size()>0){
            NocMemberEntity member = (NocMemberEntity)list.get(0);
            String ercode = member.getCol20();
            //已经生成了二维码的
            if(StringUtils.isNotEmpty(ercode)){
                //openId与手机号进行绑定
                this.memberAddOpenId(member.getId());
                String ly = (String)session.getAttribute("ly");
                return "redirect:ercode?tid="+tid+"&id="+member.getId()+"&ly="+ly;
            }else{
                //未生成二维码的
                request.setAttribute("id",member.getId());
                request.setAttribute("member",member);
                return "modules/h5/detail_en";
            }
        }else{
            //未注册
            NocMemberEntity t = new NocMemberEntity();
            t.setCol1(mobile);
            t.setTid(Integer.parseInt(tid));
            String ly = (String)session.getAttribute("ly");
            t.setLy(ly);
            //判断是否微信端注册
            Map wxUser = (HashMap)session.getAttribute(GlobalConstant.SESSION_WX_USER);
            if(wxUser!=null){
                t.setOpenId((String)wxUser.get("openId"));
            }
            nocMemberService.save(t);
            request.setAttribute("id",t.getId());
            request.setAttribute("member",t);
            return "modules/h5/detail_en";
        }
    }*/

    /**
     * 图形验证码生成
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/createImg", method = RequestMethod.GET)
    public void createImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            Session session = this.getSession();
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            VerifyUtil randomValidateCode = new VerifyUtil();
            //输出验证码图片
            String randomString = randomValidateCode.getRandcode(response);
            session.removeAttribute(RANDOMCODEKEY);
            session.setAttribute(RANDOMCODEKEY, randomString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //生成二维码图片
    @RequestMapping(value = "/createQrcode", method = RequestMethod.GET)
    public void createQrcode(String vip,String content, HttpServletResponse response) throws Exception {
        try {
            QrCodeCreateUtil.genGR(vip,content, response.getOutputStream());
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("detail")
    public String detail(String l,String id,String huiyibmb_cusname,String huiyibmb_canhren,String[] names, String[] mobiles,String huiyibmb_Department,String huiyibmb_zhiwu,
                    String huiyibmb_sexly_Value,String huiyibmb_mail,String zidingyi4_1,String zidingyi4_2,String zidingyi4_3,
                    String huiyibmb_address,String huiyibmb_col12,String huiyibmb_col13,String huiyibmb_col51,String province,String city,HttpServletRequest request) {
        Session session = this.getSession();
        String ly = request.getParameter("ly");
        String tid = request.getParameter("tid");
        Map<String,Object> pmap = new HashMap<>();
        pmap.put("id",province);
        String diqu = nocRegionService.getProvinceById(pmap).get("name")+city;
        NocMemberEntity t = new NocMemberEntity();
        t.setId(Integer.parseInt(id));
        t.setCol2(huiyibmb_cusname);
        t.setCol3(huiyibmb_canhren);
        t.setCol4(huiyibmb_Department);
        t.setCol5(huiyibmb_zhiwu);
        t.setCol6(huiyibmb_sexly_Value);
        t.setCol7(huiyibmb_mail);
        t.setCol12(huiyibmb_col12);
        t.setCol13(huiyibmb_col13);
        t.setCol52(diqu);
        if(tid.equals("11")){
            t.setCol51(huiyibmb_col51);
        }
        String col8 = "";
        if(StringUtils.isNotEmpty(zidingyi4_1)){
            col8 += zidingyi4_1;
        }
        if(StringUtils.isNotEmpty(zidingyi4_2)){
            col8 += "-"+zidingyi4_2;
        }
        if(StringUtils.isNotEmpty(zidingyi4_3)){
            col8 += "-"+zidingyi4_3;
        }
        if(StringUtils.isNotEmpty(col8)) {
            t.setCol8(zidingyi4_1 + "-" + zidingyi4_2 + "-" + zidingyi4_3);
        }
        t.setCol9(huiyibmb_address);
        //openId与手机号进行绑定
        Map wxUser = (HashMap)session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if(wxUser!=null){
            t.setOpenId((String)wxUser.get("openId"));
        }
        //添加同行人员
        doTongxing(tid,ly,names,mobiles,t,request);
        if(StringUtils.isNotEmpty(tid)){
            String result = nocWenjuanService.getWenjuan(tid);
            request.setAttribute("wenjuan",result);
        }
        request.setAttribute("id",id);
        //20200609济南展会显示问卷
        //现场渠道的观众直接显示二维码（不显示问卷）
        /*if("xianchang".equals(ly)){
            //生成二维码
            t.setCol20(this.getNextErCode());
            //以生成二维码的时间为创建时间
            t.setCreateTime(new Date());
            //是否生成vip会员
            t.setCol15(this.isCreateVipMember(ly,tid));
            nocMemberService.updateById(t);
            request.setAttribute("id",t.getId());
            request.setAttribute("member",t);
            return "modules/h5/ercode";
        }else{*/
            //问卷没有填写完成的不生成二维码
            nocMemberService.updateById(t);
        //}
        //其他渠道则显示问卷题目
        if("en".equals(l)){
            request.setAttribute("id",t.getId());
            request.setAttribute("member",t);
            return "modules/h5/ercode";
        }else {
            return "modules/h5/wenjuan";
        }
    }

    /**
     * 保存同行
     * @param tid
     * @param ly
     * @param names
     * @param mobiles
     * @param t
     * @param req
     */
    public void doTongxing(String tid,String ly,String[] names,String[] mobiles,NocMemberEntity t,HttpServletRequest req){
        //链接处理
        StringBuffer url = req.getRequestURL();
        String shortUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();
        shortUrl = shortUrl.replace("http://", "").replace("https://", "");
        //获取展会
        if(names!=null&&names.length>0) {
            for (int i = 0; i < names.length; i++) {
                NocMemberEntity tongxing = new NocMemberEntity();
                tongxing.setCol1(mobiles[i]);
                tongxing.setCol2(t.getCol2());
                tongxing.setCol3(names[i]);
                tongxing.setCol15(t.getCol15());
                tongxing.setCol52(t.getCol52());
                tongxing.setCreateTime(new Date());
                tongxing.setTid(Integer.parseInt(tid));
                tongxing.setLy(ly);
                tongxing.setTxid(t.getId());
                Map<String,Object> p = new HashMap<>();
                p.put("tid",tid);
                p.put("col1",mobiles[i]);
                List<NocMemberEntity> list = (List<NocMemberEntity>)nocMemberService.listByMap(p);
                if(list!=null&&list.size()>0){
                    //修改
                    for(NocMemberEntity mb:list){
                        mb.setCol2(t.getCol2());
                        if("xianchang".equals(ly)) {
                            mb.setCol20(this.getNextErCode());
                            mb.setCreateTime(new Date());
                        }else{
                            mb.setCol20(null);
                            mb.setCreateTime(null);
                        }
                        mb.setTxid(t.getId());
                        nocMemberService.updateById(mb);
                    }
                }else {
                    //新增
                    if("xianchang".equals(ly)) {
                        tongxing.setCol15("0");
                        tongxing.setCol20(this.getNextErCode());
                    }
                    tongxing.setCol10("同行人员");
                    nocMemberService.save(tongxing);
                    //改为问卷调查填完之后发送
                    if("xianchang".equals(ly)) {
                        //获取展会
                        NocTemplateEntity templateEntity = nocTemplateService.getById(tid);
                        String _url = shortUrl + "t/" + tongxing.getId();
                        String content = "尊敬的" + names[i] + ",您" + templateEntity.getTemplate() + "的预登记电子门票链接 " + _url + " ,请直接现场刷闸机入场";
                        this.sendContentMsg(tid + "", tongxing.getCol1(), content);
                    }
                }
            }
        }
    }

    /**
     * 问卷保存
     * @param nocMemberEntity
     * @param req
     * @return
     */
    @RequestMapping("wenjuan")
    public String wenjuan(NocMemberEntity nocMemberEntity,HttpServletRequest req){
        //判断非法请求
        NocMemberEntity member = nocMemberService.getById(nocMemberEntity.getId());
        String ly = member.getLy();
        Integer tid = member.getTid();
        Integer _tid = member.getTid();
        Integer _tid2 = nocMemberEntity.getTid();
        if(_tid.intValue()!=_tid2.intValue()){
            return "modules/h5/reg";
        }
        if(StringUtils.isEmpty(member.getCol20())) {
            //生成二维码
            nocMemberEntity.setCol20(this.getNextErCode());
            //以生成二维码的时间为创建时间
            nocMemberEntity.setCreateTime(new Date());
            //是否生成vip会员
            nocMemberEntity.setCol15(this.isCreateVipMember(ly, tid + ""));
            nocMemberService.updateById(nocMemberEntity);
            //修改同行
            Map<String, Object> p = new HashMap<>();
            p.put("tid", tid);
            p.put("txid", nocMemberEntity.getId());
            List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.listByMap(p);
            if (list != null && list.size() > 0) {
                //获取展会
                NocTemplateEntity templateEntity = nocTemplateService.getById(tid);
                //链接处理
                StringBuffer url = req.getRequestURL();
                String shortUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();
                shortUrl = shortUrl.replace("http://", "").replace("https://", "");
                //修改
                for (NocMemberEntity mb : list) {
                    mb.setCol15(this.isCreateVipMember(nocMemberEntity.getLy(), tid + ""));
                    mb.setCol20(this.getNextErCode());
                    mb.setCreateTime(new Date());
                    nocMemberService.updateById(mb);
                    //发送短信
                    //String _url = shortUrl + "t/" + mb.getId();
                    //String content = "尊敬的" + mb.getCol3() + "," + member.getCol3() + "帮您注册的" + templateEntity.getTemplate() + "的预登记电子门票链接 " + _url;
                    /*String content = _txMsg;
                    content = content.replace("{0}", mb.getCol3());
                    content = content.replace("{1}", member.getCol3());
                    content = content.replace("{2}", templateEntity.getTemplate());
                    content = content.replace("{3}", _url);
                    this.sendContentMsg(tid + "", mb.getCol1(), content);*/
                    JSONObject json = new JSONObject();
                    json.put("name",mb.getCol3());
                    json.put("name1",member.getCol3());
                    json.put("name2",templateEntity.getTemplate());
                    json.put("code",mb.getId());
                    this.sendTzMsg(tid+"",mb.getCol1(),smsTongxingSignName,smsTongxingTemplate,json.toJSONString());
                }
            }
            req.setAttribute("member",nocMemberEntity);
        }else{
            req.setAttribute("member",member);
        }
        nocMemberEntity.setCol2(member.getCol2());
        nocMemberEntity.setCol3(member.getCol3());
        req.setAttribute("id",nocMemberEntity.getId());
        return "modules/h5/ercode";
    }

    /**
     * 发送邀请短信
     * @return
     */
    @RequestMapping("doInvite")
    public String doInvite(String id,String mobile,String name,String tid,String ly,HttpServletRequest req) {
        NocMemberEntity member = nocMemberService.getById(id);
        NocTemplateEntity template = nocTemplateService.getById(tid);
        Map<String,Object> p = new HashMap<>();
        p.put("ly",ly);
        p.put("tid",tid);
        List<NocLyEntity> list = (List<NocLyEntity>) nocLyService.listByMap(p);
        if(list!=null&&list.size()>0){
            NocLyEntity nocLyEntity = list.get(0);
            //String content = name + "您好，您的朋友" + member.getCol3() + "邀请您注册为"+template.getTemplate()+"预登记观众,体验链接：" + nocLyEntity.getShortUrl();
            String content = _yqMsgl;
            if(p.get("ly").equals("xianchang")){
                content = _yqMsg;
            }
            content = content.replace("{0}", name);
            content = content.replace("{1}", member.getCol3());
            content = content.replace("{2}", template.getTemplate());
            content = content.replace("{3}", nocLyEntity.getShortUrl());
            this.sendContentMsg(tid,mobile,content);
        }
        req.setAttribute("id",id);
        req.setAttribute("member",member);
        return "modules/h5/ercode";
    }

    /**
     * 帮好友注册
     * @param id
     * @param mobile
     * @param name
     * @param company
     * @param zhiwu
     * @param email
     * @return
     */
    /*
      此方法废弃了
    @RequestMapping("doHelp")
    public String doHelp(String id, String mobile, String name, String company, String zhiwu, String email,String ly,String tid, HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("col1",mobile);
        map.put("tid",tid);
        List<NocMemberEntity> list = (List<NocMemberEntity>)nocMemberService.listByMap(map);
        if(list!=null&&list.size()>0) {
            //NocMemberEntity member = (NocMemberEntity) list.get(0);
            request.setAttribute("mobile",mobile);
            request.setAttribute("name",name);
            request.setAttribute("company",company);
            request.setAttribute("zhiwu",zhiwu);
            request.setAttribute("email",email);
            request.setAttribute("msg","该手机号已经报过名！");
            return "modules/h5/help";
        }
        NocMemberEntity t = new NocMemberEntity();
        t.setCol1(mobile);
        t.setCol2(company);
        t.setCol3(name);
        t.setCol5(zhiwu);
        t.setCol7(email);
        t.setTid(Integer.parseInt(tid));
        t.setLy(ly);
        //生成二维码的编码
        String ercode = nocMemberService.getNextErCode(_pre);
        if(StringUtils.isNotEmpty(ercode)){
            t.setCol20(_pre+ercode);
        }else{
            t.setCol20(_pre+"000001");
        }
        nocMemberService.saveOrUpdate(t);

        NocMemberEntity member = nocMemberService.getById(id);
        NocTemplateEntity template = nocTemplateService.getById(tid);
        Map<String,Object> p = new HashMap<>();
        p.put("ly",ly);
        p.put("tid",tid);
        List<NocLyEntity> lyList = (List<NocLyEntity>) nocLyService.listByMap(p);
        if(lyList!=null&&lyList.size()>0){
            String content = name+"您好，您的朋友"+member.getCol3()+"已经为您成功申请 "+template.getTemplate()+"预登记观众入场证件。您可通过关注公众号“机加小诸葛”访问底部菜单：入场登记-报到凭证找回，查看您的签到二维码。";
            this.sendContentMsg(tid,mobile,content);
        }


        request.setAttribute("id",id);
        request.setAttribute("member",nocMemberService.getById(id));
        return "modules/h5/ercode";
    }*/

    /**
     * 接收门禁数据
     * @param readId
     * @param barCode
     * @param readDate
     * @param readTime
     * @param pcName
     * @param portId
     * @param inOut
     * @param hallDoorId
     * @return
     */
    @RequestMapping("readCard")
    @ResponseBody
    public boolean readCard(String readId,String barCode,String readDate,String readTime,
                            String pcName,String portId,String inOut,String hallDoorId) {
        System.out.println("/h5/readCard?readId="+readId+"&barCode="+barCode+"&readDate="+readDate+"&readTime="+readTime+"&pcName="+pcName+"&portId="+portId+"&inOut="+inOut+"&hallDoorId="+hallDoorId);
        NocReadCardEntity t = new NocReadCardEntity();
        t.setReadId(Integer.parseInt(readId));
        t.setBarCode(barCode);
        t.setReadDate(readDate);
        t.setReadTime(readTime);
        t.setPcName(pcName);
        Integer templateId = this.getTidByBarCode(barCode);
        if(templateId!=null){
            t.setTid(templateId);
        }

        if(StringUtils.isNotEmpty(portId)){
            t.setPortId(Integer.parseInt(portId));
        }
        if(StringUtils.isNotEmpty(inOut)){
            t.setInOut(Integer.parseInt(inOut));
        }
        if(StringUtils.isNotEmpty(hallDoorId)){
            t.setHallDoorId(Integer.parseInt(hallDoorId));
        }
        nocReadCardService.save(t);

        //签到
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("col20",barCode);
        //Integer tid = this.getDefaultTemplateId();
        //if(templateId!=null){
        //    map.put("tid",templateId.toString());
        //}
        List<NocMemberEntity> list = (List<NocMemberEntity>)nocMemberService.listByMap(map);
        if(list!=null&&list.size()>0){
            NocMemberEntity member = (NocMemberEntity)list.get(0);

            NocMemberEntity t2 = new NocMemberEntity();
            t2.setId(member.getId());
            //判断是否已经签过到，已经签过的不在重复签到
            if(!"1".equals(member.getIsSign())) {
                t2.setIsSign("1");
                t2.setSignTime(new Date());
                nocMemberService.updateById(t2);
            }
            //nocMemberService.updateById(t2);
            //触发大客户到场短信
            nocMemberService.sendMemberMsg(member.getId());
            //触发展商与观众配对短信
            //nocMemberService.sendMatchMsg(member.getId());
            //nocMemberService.sendDaMemberMsg(member.getId());
            return true;
        }
        return true;
    }




    /*展会现场的打证机设备上有一个读取二维码的摄像头，观众出示入场二维码，打证机识别二维码后调用该接口，
    将信息返给打证机打印。*/
    @ResponseBody
    @RequestMapping("/getCertificate2")
    public Map<String,Object> getCertificate(@PathParam("ercode") String ercode){
        Map<String,Object> map = new LinkedHashMap<>();

        Map<String,Object> result = nocMemberService.getMemberByErCode(ercode);
        if(result!=null) {
            map.put("mobile", result.get("col1"));
            map.put("username", result.get("col3"));
            map.put("cardno", "");
            map.put("company", result.get("col2"));
            map.put("ercode", result.get("col20"));
            map.put("position", result.get("col5"));
            if (result.get("col2") == null) {
                map.put("company", "");
            }

            if (result.get("col5") == null) {
                map.put("position", "");
            }
        }
        return map;
    }


    /**
     * 名片识别保存
     * @param charname
     * @param company
     * @param JobTitle
     * @param address
     * @param mobile
     * @param aEmail
     * @param laiyuan
     * @param mingpiandizhi
     * @param ly
     * @param tid
     * @return
     */
    @RequestMapping("savemp")
    public String saveMingpian(String charname,String company,String JobTitle,String address,String mobile,String aEmail,
                                String laiyuan,String mingpiandizhi,String ly,String tid,HttpServletRequest request) {
        //防止重复提交
        if(StringUtils.isNotEmpty(mobile)&&StringUtils.isNotEmpty(tid)){
            NocMemberEntity member = this.userIsExit(mobile,tid);
            if(member==null){
                NocMemberEntity t = new NocMemberEntity();
                t.setCol1(mobile);
                t.setCol2(company);
                t.setCol3(charname);
                t.setCol5(JobTitle);
                t.setCol7(aEmail);
                t.setCol9(address);
                t.setCol10(laiyuan);
                t.setLy(ly);
                t.setTid(Integer.parseInt(tid));
                //名片地址
                t.setCol23(mingpiandizhi);
                //生成二维码
                //todo
                nocMemberService.save(t);

                request.setAttribute("id",t.getId());
                request.setAttribute("member",t);
                return "modules/h5/detail";
            }else{
                nocMemberService.updateById(member);
                request.setAttribute("id",member.getId());
                request.setAttribute("member",member);
                this.memberTongx(tid,member.getId(),request);
                return "modules/h5/detail";
            }
        }
        return "modules/h5/index";
    }

    /**
     * 判断用户是否存在
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("userIsExit")
    public R userIsExit(HttpServletRequest request){
        String tid = request.getParameter("tid");
        String mobile = request.getParameter("mobile");
        NocMemberEntity member = this.userIsExit(mobile,tid);
        if(member!=null){
            return R.ok().put("member",member);
        }else{
            return R.error("用户不存在");
        }
    }

    //网页分享
    /*@ResponseBody
    @RequestMapping(value = "/share", method = RequestMethod.GET)
    public JSONObject view(HttpServletRequest request, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        try {
            String tid = request.getParameter("tid");
            String ly = request.getParameter("ly");
            String link = "https://preg.jinnoc.com/h5/index?tid="+tid+"&ly="+ly;
            String ticket = wxjsShare.getJsTicket();
            Map<String,String> map = wxjsShare.getJsSignMap(ticket,link);
            json.put("appId", appId);
            json.put("link", link);
            json.put("nonceStr", map.get("nonceStr"));
            json.put("timestamp", map.get("timestamp"));
            json.put("signature", map.get("signature"));

            json.put("success","true");
        }catch (Exception e){
            json.put("success","false");
            json.put("msg","获取微信参数失败，请联系工程师！");
        }
        return json;
    }*/
    @RequestMapping("/test")
    public void test(){
        NocMemberEntity nocMember = new NocMemberEntity();
        nocMember.setCol1("1");
        nocMember.setCol20(this.getNextErCode());
        nocMemberService.save(nocMember);
    }

    //获取地区
    @RequestMapping("getProvince")
    @ResponseBody
    public R getProvince(){
        Map<String,Object> map = new HashMap<>();
        map.put("provinceList",nocRegionService.getProvince());
       return R.ok(map);
    }


    @RequestMapping("getCity")
    @ResponseBody
    public R getCity(String id){
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
       Map<String,Object> lastMap =new HashMap<>();
       lastMap.put("cityList",nocRegionService.getCity(map));
        return R.ok(lastMap);
    }

}
